﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace GoodMan.Infrastructure.Entities.Repository
{
    [Table("T_Dormitory")]
    public class T_Dormitory : IEntity<T_Dormitory>
    {
        #region
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column(TypeName="int")]
        public int Id { get; set; }

        [Column(TypeName="varchar")]
        [StringLength(128)]
        public string Name { get; set; }

        public int CollegeId { get; set; }

        [Column(TypeName = "varchar")]
        [StringLength(128)]
        public string Creator { get; set; }
        public DateTime CreateDate { get; set; }
        #endregion

        public override T_Dormitory Find(string key)
        {
            int id = Int32.Parse(key);
            return Find(c => c.Id == id);
        }

        public override T_Dormitory Find(System.Linq.Expressions.Expression<Func<T_Dormitory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var item = ctx.Dormitory.FirstOrDefault(where);
                if (item != null)
                {
                    this.CollegeId = item.CollegeId;
                    this.CreateDate = item.CreateDate;
                    this.Creator = item.Creator;
                    this.Id = item.Id;
                    this.Name = item.Name;
                    return this;
                }
                return null;
            }
        }

        public override bool Any(System.Linq.Expressions.Expression<Func<T_Dormitory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.Dormitory.Any(where);
            }
        }

        public override T_Dormitory FindLast(System.Linq.Expressions.Expression<Func<T_Dormitory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var item = ctx.Dormitory.OrderByDescending(c=>c.Id).FirstOrDefault(where);
                if (item != null)
                {
                    this.CollegeId = item.CollegeId;
                    this.CreateDate = item.CreateDate;
                    this.Creator = item.Creator;
                    this.Id = item.Id;
                    this.Name = item.Name;
                    return this;
                }
                return null;
            }
        }
    }
}
